#include <sys/inotify.h>
#include <sys/ioctl.h>
#include <gtk/gtklabel.h>
#include <stdlib.h>
#include "getstatus.h"
#include <unistd.h>

extern int ino_fd, wd;

gboolean in_check(GtkWidget *label)
{
    char *buf;
    struct inotify_event *ev;
    unsigned int bytes_to_parse, p;
    do
    {
        if (ioctl(ino_fd, FIONREAD, &bytes_to_parse) == -1)
        {
            perror("ioctl(): ");
            return FALSE;
        }
        if (bytes_to_parse==0) return TRUE; //don't block if there's nothing to parse
    } while (bytes_to_parse < sizeof(struct inotify_event));
    buf = (char *)malloc(bytes_to_parse);
    if (read(ino_fd, buf, bytes_to_parse) == -1)
    {
        perror("read(): ");
        return FALSE;
    }
    for (p = 0; p < bytes_to_parse; p += ev->len + 16)
    {
        ev = (struct inotify_event *)(buf + p);
        if (ev->mask&IN_MODIFY) update_status(label);
        if (ev->mask&(IN_IGNORED|IN_Q_OVERFLOW|IN_UNMOUNT))
        {
            fprintf(stderr, "An error occured with inotify watch!\n");
            return FALSE;
        }

    }
    free(buf);
    return TRUE;
}
